<?php
// +----------------------------------------------------------------------
// | WWW.0771MC.COM 广西南宁市铭成龙毅网络科技有限公司 出品
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://WWW.0771MC.COM All rights reserved.
// +----------------------------------------------------------------------
// | Author: 铭成龙毅 <service@0771mc.com> <http://www.0771MC.com>
// +----------------------------------------------------------------------
namespace Install\Controller;
use Think\Controller;
class IndexController extends Controller {
	protected function _initialize() {
		//防止恶意安装
		if (is_file('./Data/install.lock')) {
			header('Location: ./index.php');
			exit ;
		}
	}

	public function index() {
		$this -> assign('step_curr', 'eula');
		if (IS_POST) {
			$accept = I('accept');
			if (!$accept) {
				$error_msg = "请先阅读并同意安装协议";
				$this -> assign('error_msg', $error_msg);
				$this -> display();
			} else {
				$this -> redirect('check');
			}
		} else {
			$this -> display();
		}
	}

	public function check() {

		$flag = true;
		//检测文件夹权限
		$check_file = array('./Uploads', './Data', './Runtime', './Apps/Common/Conf', './Apps/Common/Conf/config.site.php', './Apps/Common/Conf/config.pay.php', './Apps/Common/Conf/config.url.php', './Apps/Common/Conf/pics.php', './Apps/Html', './Data/backupdata', );
		$error = array();
		foreach ($check_file as $file) {
			$path_file = $file;
			if (!file_exists($path_file)) {
				$error[] = $file . "不存在";
				$flag = false;
				continue;
			}
			if (!is_writable($path_file)) {
				$error[] = $file . "不可写";
				$flag = false;
			}
		}
		if (!function_exists('curl_getinfo')) {
			$error[] = "系统不支持curl";
			$flag = false;
		}

		if (!function_exists('gd_info')) {
			$error[] = "系统不支持GD";
			$flag = false;
		}

		$dir_obj = new \Think\Dir();
		is_dir('./Runtime') && $dir_obj -> delDir('./Runtime');

		if (!$flag) {
			$this -> assign('error', $error);
			$this -> assign('step_curr', 'check');
			$this -> display('check');
		} else {
			$this -> redirect('setconf');
		}
	}

	public function setconf() {

		$this -> assign('step_curr', 'setconf');
		if (IS_POST) {
			foreach ($_POST as $key => $val) {
				$this -> assign($key, $val);
			}
			extract($_POST);
			if (!$db_host || !$db_port || !$db_name || !$db_user || !$db_prefix || !$admin_user || !$admin_pass) {
				$this -> assign('error_msg', "请完整填写配置信息");
				$this -> display();
				exit ;
			}
			if ($admin_pass != $admin_pass_confirm) {
				$this -> assign('error_msg', "管理员密码不一致");
				$this -> display();
				exit ;
			}
			//试着连接数据库
			$conn = @mysql_connect($db_host . ':' . $db_port, $db_user, $db_pass);
			if (!$conn) {
				$this -> assign('error_msg', "数据库连接失败，请检查数据库配置信息。");
				$this -> display();
				exit ;
			}
			$selected_db = @mysql_select_db($db_name);
			if ($selected_db) {
				//如果数据库存在 并且里面安装过   提示是否覆盖
				$query = @mysql_query("SHOW TABLES LIKE '{$db_prefix}%'");
				$was_install = false;
				while ($row = mysql_fetch_assoc($query)) {
					$was_install = true;
					break;
				}
				if ($was_install && !isset($force_install)) {
					$this -> assign('database_name_tip', '<input type="checkbox" name="force_install" id="force_install" class="input_checkbox" value="1" /><font color="red">此数据库已经安装过铭成龙毅企业网站管理系统，继续安装可能会清空数据</font>');
					$this -> display();
					exit ;
				} else {
					$this -> _set_temp($_POST);
					$this -> redirect('install');
				}
			} else {
				if (mysql_get_server_info($conn) > '4.1') {
					$charset = C('DEFAULT_CHARSET');
					$sql = "CREATE DATABASE IF NOT EXISTS `{$db_name}` DEFAULT CHARACTER SET " . str_replace('-', '', $charset);
				} else {
					$sql = "CREATE DATABASE IF NOT EXISTS `{$db_name}`";
				}
				if (!mysql_query($sql, $conn)) {
					$this -> assign('error_msg', '创建数据库失败！');
					$this -> display();
					exit ;
				}
				$this -> _set_temp($_POST);
				$this -> redirect('install');
			}
		} else {
			$this -> assign('database_name_tip', '用于安装程序的数据库，若不存在则创建');
			$this -> assign('db_host', 'localhost');
			$this -> assign('db_port', '3306');
			$this -> assign('db_user', 'root');
			$this -> assign('db_name', '');
			$this -> assign('db_prefix', 'wowo_');

			$this -> assign('admin_user', 'wowocms');
			$this -> assign('db_pass', '');
			$this -> assign('admin_pass', '');
			$this -> assign('admin_pass_confirm', '');
			$this -> assign('admin_email', '');
			$this -> display();
		}
	}

	public function install() {
		$this -> assign('step_curr', 'install');
		$this -> display();
	}

	public function finish_done() {
		$charset = 'utf8';
		header('Content-type:text/html;charset=' . $charset);
		$temp_info = F('temp_data');
		$conn = mysql_connect($temp_info['db_host'] . ':' . $temp_info['db_port'], $temp_info['db_user'], $temp_info['db_pass']);
		$version = mysql_get_server_info();
		$charset = str_replace('-', '', $charset);
		if ($version > '4.1') {
			if ($charset != 'latin1') {
				mysql_query("SET character_set_connection={$charset}, character_set_results={$charset}, character_set_client=binary", $conn);
			}
			if ($version > '5.0.1') {
				mysql_query("SET sql_mode=''", $conn);
			}
		}
		$selected_db = mysql_select_db($temp_info['db_name'], $conn);
		$this -> _show_process("创建数据表开始...");
		$sqls = $this -> _get_sql(MODULE_PATH . 'Data/create_table.sql');
		foreach ($sqls as $sql) {
			$sql = str_replace('`wowocms_', '`' . $temp_info['db_prefix'], $sql);
			$run = mysql_query($sql, $conn);
			if (substr($sql, 0, 12) == 'CREATE TABLE') {
				$table_name = $temp_info['db_prefix'] . preg_replace("/CREATE TABLE `" . $temp_info['db_prefix'] . "([a-z0-9_]+)` .*/is", "\\1", $sql);
				$this -> _show_process(sprintf("创建数据表 %s 成功！", $table_name));
			}
		}
		$this -> _show_process("添加初始数据开始...");
		$sqls = $this -> _get_sql(MODULE_PATH . 'Data/initdata.sql');
		$passwordinfo = get_password($temp_info['admin_pass']);
		$sqls[] = "INSERT INTO `" . $temp_info['db_prefix'] . "members` (`username`, `password`, `encrypt`, `status`) VALUES " . "('" . $temp_info['admin_user'] . "', '" . $passwordinfo['password'] . "', '" . $passwordinfo['encrypt'] . "', 0);";
		$sqls[] = "INSERT INTO `" . $temp_info['db_prefix'] . "auth_group_access` (`uid`, `group_id`) VALUES " . "(1, 1);";

		foreach ($sqls as $sql) {
			$sql = str_replace('`wowocms_', '`' . $temp_info['db_prefix'], $sql);
			if (substr($sql, 0, 11) == 'INSERT INTO') {
				$table_name = $temp_info['db_prefix'] . preg_replace("/INSERT INTO `" . $temp_info['db_prefix'] . "([a-z0-9_]+)` .*/is", "\\1", $sql);
				$run = mysql_query($sql, $conn);
			}
		}

		$this -> _show_process("初始数据添加成功！");
		//修改配置文件
		$config_file = './Apps/Common/Conf/config.db.php';
		$config_data['DB_TYPE'] = 'mysql';
		$config_data['DB_HOST'] = $temp_info['db_host'];
		$config_data['DB_NAME'] = $temp_info['db_name'];
		$config_data['DB_USER'] = $temp_info['db_user'];
		$config_data['DB_PWD'] = $temp_info['db_pass'];
		$config_data['DB_PORT'] = $temp_info['db_port'];
		$config_data['DB_PREFIX'] = $temp_info['db_prefix'];
		$config_data['DB_CHARSET'] = "utf8";
		file_put_contents($config_file, "<?php\r\nreturn " . var_export($config_data, true) . ";");

		//安装完毕
		$this -> _show_process("恭喜您，最新版程序已经安装完成！", 'parent.install_successed();');
		return false;
	}

	public function finish() {
		$webhost = "http://" . $_SERVER['HTTP_HOST'];
		$cookie_encode = get_randomstr(8);
		$conf = file_get_contents('./Apps/Install/Data/config.php');
		$conf = str_replace("[WEBURL]", $webhost, $conf);
		$conf = str_replace("[COOKIE_ENCODE]", $cookie_encode, $conf);
		file_put_contents('./Apps/Common/Conf/config.site.php', $conf);
		$this -> assign('step_curr', 'finish');
		touch('./Data/install.lock');
		$this -> display();
	}

	private function _show_process($msg, $script = '') {
		echo '<script type="text/javascript">parent.show_process(\'<p><span>' . $msg . '</span></p>\');' . $script . '</script>';
		flush();
		ob_flush();
	}

	private function _get_sql($sql_file) {
		$contents = file_get_contents($sql_file);
		$contents = str_replace("\r\n", "\n", $contents);
		$contents = trim(str_replace("\r", "\n", $contents));
		$return_items = $items = array();
		$items = explode(";\n", $contents);
		foreach ($items as $item) {
			$return_item = '';
			$item = trim($item);
			$lines = explode("\n", $item);
			foreach ($lines as $line) {
				if (isset($line[1]) && $line[0] . $line[1] == '--') {
					continue;
				}
				$return_item .= $line;
			}
			if ($return_item) {
				$return_items[] = $return_item;
				//.";";
			}
		}
		return $return_items;
	}

	private function _set_temp($temp_data) {
		F('temp_data', $temp_data);
	}

}
